<template>
  <div class="play-box">
    <div class="title">{{ renderData['playTypeName'] }}</div>
    <SubTab :data="renderData.lotteryPlayTypeList" @selectPlayType="selectPlayType" />
    <div class="play-odds">
      <LhcButton
        v-for="(item, index) in renderData.lotteryPlayTypeList[currentPlayTypeIndex].cachePlayList"
        :class="setClass(item)"
        :data="item"
        :key="index"
        @selectOdds="selectNumber(item)"
      />
    </div>
  </div>
</template>

<script lang="ts" setup>
import { computed, watch, unref } from 'vue'
import LhcButton from './lhc-button.vue'
import SubTab from './lhc-tab.vue'
import { showToast } from 'vant'
import { EM_RULE_LIST, tabEnum } from '@/components/game/tpl-lhc/lhc-constant'
import { $utils } from '@/utils'
import { submitBetNow } from '@/api'

import { useInvestStore } from '@/stores/invest'
import { useCommonLogic } from '@/components/game/tpl-lhc/game/useCommonLogic'

import { useGameStore } from '@/stores/game'

const gameStore = useGameStore()

const currentHandicapCode = computed(() => gameStore.currentHandicapCode)

const props = defineProps(['renderData'])

const {
  init,
  selectPlayType,
  selectedList,
  updateInvestList,
  fillLastNumber,
  notifyParentInvestList,
  currentPlayTypeIndex,
  getParams,
} = useCommonLogic(props)

const investStore = useInvestStore()

const currentSubName = computed(() => props.renderData.lotteryPlayTypeList[currentPlayTypeIndex.value].playTypeName)

const itemKey = computed(() =>
  currentGameName.value === '连码' || currentGameName.value === '自选不中' ? 'number' : 'playCode',
)

const currentGameName = computed(() => props.renderData.playTypeName)

watch(currentGameName, () => {
  selectPlayType(0)
})

const ermianCheckRules = ({ playCode }) => {
  if (currentSubName.value !== '两面') return null
  const set = new Set([...selectedList.value.map((item) => item.playCode), playCode])
  const tip = EM_RULE_LIST.find(({ list }) => list.every((code) => set.has(code)))?.tip
  tip && showToast(tip)
  return tip
}

const lianxiaoCheckRules = () => {
  if (currentGameName.value !== '连肖') return false
  if (currentPlayTypeIndex.value >= selectedList.value.length) return false
  return showToast('超过最大选择数量')
}

const lianmaCheckRules = () => {
  if (currentGameName.value !== '连码') return false
  if (currentPlayTypeIndex.value + 1 >= selectedList.value.length) return false
  return showToast('超过最大选择数量')
}

const zixuanbuzhongCheckRules = () => {
  if (currentGameName.value !== '自选不中' && selectedList.value.length === 11) {
    showToast(`最多选择11个号码`)
    return true
  }
  return false
}

const betContentParams = () => {
  const { lotteryCode, playTypeCode } = props.renderData
  const { sonPlayTypeCode, playCode, betAmount } = selectedList.value[0]
  const betContent = selectedList.value.reduce((str, item) => ((str += item[itemKey.value] + ' '), str), '')
  return [{ lotteryCode, playTypeCode, sonPlayTypeCode, playCode, betAmount, betContent }]
}

const selectNumber = (item) => {
  const key = currentGameName.value === '连肖' ? 'playName' : itemKey.value
  item.betAmount = investStore.getSingleInvestMoney
  item['spliceName'] = `${currentSubName.value}#${item[key]}`

  if (ermianCheckRules(item)) return

  const index = selectedList.value.findIndex((selItem) => selItem[itemKey.value] === item[itemKey.value])

  if (index === -1) {
    //
    if (lianxiaoCheckRules()) return
    //
    if (lianmaCheckRules()) return
    //
    if (zixuanbuzhongCheckRules()) return

    selectedList.value.push(item)
  } else {
    selectedList.value.splice(index, 1)
  }

  notifyParentInvestList(selectedList.value)
}

const betCheck = () => {
  if (currentGameName.value !== '自选不中') return null
  const { playTypeCode } = props.renderData.lotteryPlayTypeList[currentPlayTypeIndex.value]
  const minLength = tabEnum[playTypeCode]

  if (selectedList.value.length < minLength || selectedList.value.length > 11) {
    showToast(`请选择${minLength}~11个号码`)
    return true
  }

  return null
}

const betNow = async () => {
  if (!investStore.getInvestBtnText.canBat) {
    fillLastNumber()
    return
  }
  //
  if (betCheck()) return
  //
  if (!$utils.verifyBetAmount(selectedList.value)) return

  const { lotteryCode } = props.renderData
  let params: any = {
    lotteryCode,
    orderDetails: currentGameName.value === '特码' ? getParams() : betContentParams(),
  }

  const capCode = unref(currentHandicapCode.value)
  if (capCode) params.handicapCode = capCode

  try {
    await submitBetNow(params)
    investStore.setLastInvestList(selectedList.value)
    init()
    showToast('下注成功')
  } catch (e) {
    console.log(e)
  }
}
// 生效 设置 样式 zodiac 圆圈数组 样式 circle
const setClass = (item) => {
  const isSelected = selectedList.value.includes(item)
  const className =
    currentGameName.value === '自选不中' ? 'circle' : currentGameName.value === '连肖' ? 'zodiac' : 'text'
  return `${isSelected ? 'selected ' : ''}${className}`
}

defineExpose({
  betNow,
  updateInvestList,
})
</script>

<style scoped lang="less">
@import url('./game.less');
</style>
